const db = require('./db');

class AllowanceDao {
    // 获取用户的加班记录列表
    static async getAllowanceByUserId(userId) {
        const sql = `
            SELECT 
                rec_id as id,
                rec_user_id as user_id,
                rec_ot_hour as allowance_hour,
                CASE rec_ot_type_id
                    WHEN 5 THEN '普通加班'
                    WHEN 6 THEN '节假日加班'
                    ELSE '未知类型'
                END as allowance_type,
                rec_ot_type_id as allowance_type_id,
                rec_date -- 直接选中原始日期字段
            FROM allowance_records 
            WHERE rec_user_id = ?
            ORDER BY rec_date DESC
        `;
        try {
            console.log('AllowanceDao.getAllowanceByUserId: 接收到用户ID:', userId);
            console.log('AllowanceDao.getAllowanceByUserId: 执行SQL:', sql);
            console.log('AllowanceDao.getAllowanceByUserId: 参数:', [userId]);
            const result = await db.query(sql, [userId]); // 直接获取结果
            console.log('AllowanceDao.getAllowanceByUserId: 原始查询结果:', result); // 新增日志
            
            let rows = [];
            if (Array.isArray(result)) {
                rows = result; // 如果是数组，直接使用
            } else if (result && typeof result === 'object') {
                // 如果是单个对象（一条记录），放入数组
                rows = [result];
            } else {
                 console.error('AllowanceDao.getAllowanceByUserId: 数据库查询结果不是预期的格式:', result); // 修改日志
                 // 保持rows为空数组
            }

            console.log('AllowanceDao.getAllowanceByUserId: 处理后的rows:', rows); // 新增日志

            // 在应用层格式化日期
            const formattedRows = rows.map(row => {
                return {
                    ...row,
                    year_month: row.rec_date ? new Date(row.rec_date).toISOString().split('T')[0] : null // 简单的日期格式化
                };
            });
            return formattedRows;
        } catch (error) {
            console.error('AllowanceDao.getAllowanceByUserId: 获取加班记录失败:', error);
            throw error;
        }
    }

    // 添加加班记录
    static async addAllowance(allowance) {
        const sql = `
            INSERT INTO allowance_records 
            (rec_user_id, rec_ot_hour, rec_ot_type_id, rec_date) 
            VALUES (?, ?, ?, ?)
        `;
        const params = [
            allowance.user_id,
            allowance.allowance_hour,
            allowance.allowance_type === '普通加班' ? 5 : 6,
            allowance.year_month
        ];
        try {
            console.log('AllowanceDao.addAllowance: 添加加班记录:', allowance);
            console.log('AllowanceDao.addAllowance: 执行SQL:', sql);
            console.log('AllowanceDao.addAllowance: 参数:', params);
            const result = await db.query(sql, params); // 移除数组解构
            console.log('AllowanceDao.addAllowance: 添加结果:', result);
            return result;
        } catch (error) {
            console.error('AllowanceDao.addAllowance: 添加加班记录失败:', error);
            throw error;
        }
    }

    // 更新加班记录
    static async updateAllowance(id, allowance) {
        const sql = `
            UPDATE allowance_records 
            SET rec_ot_hour = ?,
                rec_ot_type_id = ?,
                rec_date = ?
            WHERE rec_id = ? AND rec_user_id = ?
        `;
        const params = [
            allowance.allowance_hour,
            allowance.allowance_type === '普通加班' ? 5 : 6,
            allowance.year_month,
            id,
            allowance.user_id
        ];
        try {
            console.log('AllowanceDao.updateAllowance: 更新加班记录:', { id, allowance });
            console.log('AllowanceDao.updateAllowance: 执行SQL:', sql);
            console.log('AllowanceDao.updateAllowance: 参数:', params);
            const result = await db.query(sql, params); // 移除数组解构
            console.log('AllowanceDao.updateAllowance: 更新结果:', result);
            return result;
        } catch (error) {
            console.error('AllowanceDao.updateAllowance: 更新加班记录失败:', error);
            throw error;
        }
    }

    // 删除加班记录
    static async deleteAllowance(id, userId) {
        const sql = `
            DELETE FROM allowance_records 
            WHERE rec_id = ? AND rec_user_id = ?
        `;
        try {
            console.log('AllowanceDao.deleteAllowance: 删除加班记录:', { id, userId });
            console.log('AllowanceDao.deleteAllowance: 执行SQL:', sql);
            console.log('AllowanceDao.deleteAllowance: 参数:', [id, userId]);
            const result = await db.query(sql, [id, userId]); // 移除数组解构
            console.log('AllowanceDao.deleteAllowance: 删除结果:', result);
            return result;
        } catch (error) {
            console.error('AllowanceDao.deleteAllowance: 删除加班记录失败:', error);
            throw error;
        }
    }

    // 获取单条加班记录
    static async getAllowanceById(id, userId) {
        const sql = `
            SELECT 
                rec_id as id,
                rec_user_id as user_id,
                rec_ot_hour as allowance_hour,
                CASE rec_ot_type_id
                    WHEN 5 THEN '普通加班'
                    WHEN 6 THEN '节假日加班'
                    ELSE '未知类型'
                END as allowance_type,
                rec_ot_type_id as allowance_type_id,
                rec_date
            FROM allowance_records 
            WHERE rec_id = ? AND rec_user_id = ?
        `;
        try {
            console.log('AllowanceDao.getAllowanceById: 获取单条加班记录:', { id, userId });
            console.log('AllowanceDao.getAllowanceById: 执行SQL:', sql);
            console.log('AllowanceDao.getAllowanceById: 参数:', [id, userId]);
            const result = await db.query(sql, [id, userId]); // 直接获取结果
            console.log('AllowanceDao.getAllowanceById: 原始查询结果:', result); // 新增日志
            
            let record = null;
            if (Array.isArray(result) && result.length > 0) {
                record = result[0]; // 如果是数组且有元素，取第一个
            } else if (result && typeof result === 'object') {
                 // 如果是单个对象（一条记录）
                record = result;
            } else {
                 console.error('AllowanceDao.getAllowanceById: 数据库查询结果不是预期的格式或为空:', result); // 修改日志
            }

            console.log('AllowanceDao.getAllowanceById: 处理后的record:', record); // 新增日志

            // 在应用层格式化日期
            if (record && record.rec_date) {
                 record.year_month = new Date(record.rec_date).toISOString().split('T')[0];
            } else if(record) { // 即使没有rec_date也确保year_month字段存在
                 record.year_month = null;
            }
            
            if (record) { // 确保record存在再删除属性
                delete record.rec_date; // 移除原始日期字段
            }
            
            return record;
        } catch (error) {
            console.error('AllowanceDao.getAllowanceById: 获取单条加班记录失败:', error);
            throw error;
        }
    }
}

module.exports = AllowanceDao;